<template>
  <div class="attachment-management">
         <!-- 页面标题和操作按钮 -->
     <div class="page-header">
       <div class="title-section">
         <h2 class="page-title">附件管理</h2>
         <div class="auth-status">
           <el-tag :type="authStatus.type" size="small">
             {{ authStatus.text }}
           </el-tag>
         </div>
       </div>
      <div class="action-section">
        <el-button type="primary" @click="showUploadDialog">
          <el-icon><Plus /></el-icon>
          订单附件添加
        </el-button>
        <el-button type="danger" @click="deleteSelected" :disabled="!hasSelected">
          <el-icon><Delete /></el-icon>
          删除
        </el-button>
        <el-button type="success" @click="exportSelected" :disabled="!hasSelected">
          <el-icon><Download /></el-icon>
          导出附件
        </el-button>
        <el-button type="warning" @click="printSelected" :disabled="!hasSelected">
          <el-icon><Printer /></el-icon>
          打印附件
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-section">
      <el-form :inline="true" :model="searchForm" class="search-form">
                 <el-form-item label="订单ID">
           <el-input 
             v-model="searchForm.soId" 
             placeholder="请输入数字订单ID" 
             type="number"
             min="1"
             clearable>
           </el-input>
         </el-form-item>
        <el-form-item label="附件类型">
          <el-select v-model="searchForm.attachmentType" placeholder="请选择附件类型" clearable>
            <el-option
              v-for="type in attachmentTypes"
              :key="type.typeCode"
              :label="type.typeName"
              :value="type.typeCode">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上传人">
          <el-input v-model="searchForm.uploader" placeholder="请输入上传人" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchAttachments">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

           <!-- 附件列表 -->
       <div class="attachment-list">
         <el-table
           :data="attachmentList"
           @selection-change="handleSelectionChange"
           v-loading="loading"
           border
           stripe>
           <el-table-column type="selection" width="55"></el-table-column>
           <el-table-column prop="attachmentName" label="文件名称" min-width="200">
             <template #default="{ row }">
               <el-link 
                 type="primary" 
                 @click="previewFile(row)"
                 :underline="false">
                 {{ row.attachmentName }}
               </el-link>
             </template>
           </el-table-column>
           <el-table-column prop="attachmentType" label="附件类型" width="120">
             <template #default="{ row }">
               <el-tag :type="getTypeTagType(row.attachmentType)">
                 {{ getTypeName(row.attachmentType) }}
               </el-tag>
             </template>
           </el-table-column>
           <el-table-column prop="fileSize" label="文件大小" width="120">
             <template #default="{ row }">
               {{ formatFileSize(row.fileSize) }}
             </template>
           </el-table-column>
           <el-table-column prop="uploader" label="上传人" width="100"></el-table-column>
           <el-table-column prop="uploadTime" label="上传时间" width="180">
             <template #default="{ row }">
               {{ formatDateTime(row.uploadTime) }}
             </template>
           </el-table-column>
           <el-table-column prop="description" label="描述" min-width="150" show-overflow-tooltip></el-table-column>
           <el-table-column label="操作" width="200" fixed="right">
             <template #default="{ row }">
               <el-button size="small" type="warning" @click="editDescription(row)">
                 <el-icon><Edit /></el-icon>
                 编辑
               </el-button>
               <el-button size="small" type="danger" @click="deleteFile(row)">
                 <el-icon><Delete /></el-icon>
                 删除
               </el-button>
             </template>
           </el-table-column>
         </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.pageNo"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total">
        </el-pagination>
      </div>
    </div>

    <!-- 上传对话框 -->
    <el-dialog
      v-model="uploadDialogVisible"
      title="订单附件添加"
      width="600px"
      :close-on-click-modal="false"
      :append-to-body="true"
      :lock-scroll="false">

             <el-form :model="uploadForm" :rules="uploadRules" ref="uploadForm" label-width="120px">
         <el-form-item label="订单ID" prop="soId">
           <el-input 
             v-model="uploadForm.soId" 
             placeholder="请输入数字订单ID，如：123"
             type="number"
             min="1"
             @input="validateSoId">
           </el-input>
           <div class="form-tip">订单ID必须是正整数</div>
         </el-form-item>
         
         <el-form-item label="附件类型" prop="attachmentType">
           <el-select 
             v-model="uploadForm.attachmentType" 
             placeholder="请选择附件类型"
             style="width: 100%">
             <el-option
               v-for="type in attachmentTypes"
               :key="type.typeCode"
               :label="type.typeName"
               :value="type.typeCode">
             </el-option>
           </el-select>
         </el-form-item>
         
         <el-form-item label="上传人" prop="uploader">
           <el-input 
             v-model="uploadForm.uploader" 
             placeholder="请输入上传人姓名">
           </el-input>
         </el-form-item>
         
         <el-form-item label="附件描述" prop="description">
           <el-input
             v-model="uploadForm.description"
             type="textarea"
             :rows="3"
             placeholder="请输入附件描述">
           </el-input>
         </el-form-item>
        <el-form-item label="上传文件" prop="files">
          <el-upload
            ref="upload"
            :auto-upload="false"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :before-upload="beforeUpload"
            :file-list="uploadForm.fileList"
            :limit="10"
            multiple
            drag>
            <el-icon class="el-icon-upload"><Upload /></el-icon>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                         <template #tip>
               <div class="el-upload__tip">
                 支持的文件类型：PDF、DOC、DOCX、XLS、XLSX、JPG、PNG、ZIP等
                 <br>单个文件大小不超过10MB，最多可上传10个文件
               </div>
             </template>
          </el-upload>
                     <div v-if="uploadForm.fileList.length > 0" class="file-list-info">
             已选择 {{ uploadForm.fileList.length }} 个文件
             <div class="file-details">
               <div v-for="(file, index) in uploadForm.fileList" :key="index" class="file-item">
                 <span class="file-name">{{ file.name }}</span>
                 <span class="file-size">{{ formatFileSize(file.size || file.raw?.size) }}</span>
                 <span v-if="file.raw && (file.raw.size || file.size) >= 100" class="file-status valid">✓ 有效</span>
                 <span v-else class="file-status invalid">✗ 无效</span>
               </div>
             </div>
             <div class="file-actions">
               <el-button size="small" type="warning" @click="clearFiles">清空文件</el-button>
               <el-button size="small" type="primary" @click="reSelectFiles">重新选择</el-button>
             </div>
           </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="uploadDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitUpload" :loading="uploading">
            {{ uploading ? '上传中...' : '开始上传' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑描述对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑附件描述"
      width="500px">
      <el-form :model="editForm" :rules="editRules" ref="editForm" label-width="100px">
        <el-form-item label="文件名称">
          <span>{{ editForm.attachmentName }}</span>
        </el-form-item>
        <el-form-item label="附件描述" prop="description">
          <el-input
            v-model="editForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入附件描述">
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 文件预览对话框 -->
    <el-dialog
      v-model="previewDialogVisible"
      title="文件预览"
      width="80%"
      :close-on-click-modal="false">
      <div class="preview-content">
                 <div class="preview-header">
           <h3>{{ previewFileData.attachmentName }}</h3>
           <div class="preview-actions">
             <el-button type="primary" @click="downloadPreviewFile">
               <el-icon><Download /></el-icon>
               下载
             </el-button>
             <el-button type="warning" @click="printPreviewFile">
               <el-icon><Printer /></el-icon>
               打印
             </el-button>
           </div>
         </div>
         <div class="preview-body">
           <!-- 图片预览 -->
           <div v-if="isImageFile" class="image-preview">
             <img :src="previewUrl" :alt="previewFileData.attachmentName" />
           </div>
           <!-- PDF预览 -->
           <div v-else-if="isPdfFile" class="pdf-preview">
             <iframe :src="previewUrl" width="100%" height="600px"></iframe>
           </div>
           <!-- 其他文件 -->
           <div v-else class="other-preview">
                            <div class="file-info">
                 <el-icon class="file-icon"><Document /></el-icon>
                 <p>文件类型：{{ previewFileData.attachmentType }}</p>
                 <p>文件大小：{{ formatFileSize(previewFileData.fileSize) }}</p>
                 <p>上传时间：{{ formatDateTime(previewFileData.uploadTime) }}</p>
                 <p>描述：{{ previewFileData.description || '无' }}</p>
               </div>
           </div>
         </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import salesApi from '@/api/sales'
import { 
  Plus, 
  InfoFilled, 
  Warning, 
  Delete, 
  Download, 
  Printer, 
  Search, 
  Refresh, 
  Edit, 
  Document, 
  Upload 
} from '@element-plus/icons-vue'

export default {
  name: 'AttachmentManagement',
  components: {
    Plus,
    InfoFilled,
    Warning,
    Delete,
    Download,
    Printer,
    Search,
    Refresh,
    Edit,
    Document,
    Upload
  },
  data() {
    return {
      // 搜索表单
      searchForm: {
        soId: '',
        attachmentType: '',
        uploader: ''
      },
      // 附件列表
      attachmentList: [],
      // 选中的附件
      selectedAttachments: [],
      // 附件类型配置
      attachmentTypes: [],
      // 加载状态
      loading: false,
      // 分页信息
      pagination: {
        pageNo: 1,
        pageSize: 10,
        total: 0
      },
      // 上传对话框
      uploadDialogVisible: false,
             uploadForm: {
         soId: '',
         attachmentType: '',
         uploader: '',
         description: '',
         fileList: []
       },
       uploadRules: {
         soId: [
           { required: true, message: '请输入订单ID', trigger: 'blur' },
           { 
             pattern: /^\d+$/, 
             message: '订单ID必须是数字', 
             trigger: 'blur' 
           }
         ],
         attachmentType: [
           { required: true, message: '请选择附件类型', trigger: 'change' }
         ],
         uploader: [
           { required: true, message: '请输入上传人', trigger: 'blur' }
         ]
       },
      uploading: false,
      uploadAction: '/api/sales/attachment/upload/batch',
      uploadHeaders: {
        'X-Requested-With': 'XMLHttpRequest'
      },
      // 编辑对话框
      editDialogVisible: false,
      editForm: {
        id: '',
        attachmentName: '',
        description: ''
      },
      editRules: {
        description: [
          { required: true, message: '请输入附件描述', trigger: 'blur' }
        ]
      },
                    // 预览对话框
        previewDialogVisible: false,
        previewFileData: {},
        previewUrl: '',
        // 认证状态
        authStatus: {
          type: 'info',
          text: '检查中...'
        }
     }
  },
  computed: {
    hasSelected() {
      return this.selectedAttachments.length > 0
    },
         isImageFile() {
       const ext = this.getFileExtension(this.previewFileData.attachmentName)
       return ['jpg', 'jpeg', 'png', 'gif', 'bmp'].includes(ext.toLowerCase())
     },
     isPdfFile() {
       const ext = this.getFileExtension(this.previewFileData.attachmentName)
       return ext.toLowerCase() === 'pdf'
     }
  },
     mounted() {
     console.log('AttachmentManagement 组件已挂载')
     console.log('初始 uploadDialogVisible:', this.uploadDialogVisible)
     
     // 检查认证状态
     this.checkAuthStatus()
     
     this.loadAttachmentTypes()
     this.loadAttachments()
   },
  methods: {
    // 检查认证状态
    checkAuthStatus() {
      const token = localStorage.getItem('token')
      if (!token) {
        this.authStatus = {
          type: 'danger',
          text: '未登录'
        }
        this.$message.error('请先登录系统')
        // 跳转到登录页
        this.$router.push('/')
        return false
      }
      
      this.authStatus = {
        type: 'success',
        text: '已认证'
      }
      console.log('认证状态正常，token存在')
      return true
    },

    // 加载附件类型配置
    async loadAttachmentTypes() {
      try {
        const response = await salesApi.attachmentApi.getAttachmentTypeConfigs()
        if (response.success) {
          this.attachmentTypes = response.data
        }
      } catch (error) {
        console.error('加载附件类型配置失败:', error)
      }
    },

    // 加载附件列表
    async loadAttachments() {
      this.loading = true
      try {
        const params = {
          pageNo: this.pagination.pageNo,
          pageSize: this.pagination.pageSize,
          soId: this.searchForm.soId || undefined,
          attachmentType: this.searchForm.attachmentType || undefined,
          uploader: this.searchForm.uploader || undefined
        }
        
        const response = await salesApi.attachmentApi.pageAttachments(params)
        if (response.success) {
          this.attachmentList = response.data.records
          this.pagination.total = response.data.total
        } else {
          this.$message.error(response.message || '加载附件列表失败')
        }
      } catch (error) {
        console.error('加载附件列表失败:', error)
        this.$message.error('加载附件列表失败')
      } finally {
        this.loading = false
      }
    },

    // 搜索附件
    searchAttachments() {
      this.pagination.pageNo = 1
      this.loadAttachments()
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        soId: '',
        attachmentType: '',
        uploader: ''
      }
      this.searchAttachments()
    },

    // 测试按钮方法
    testButton() {
      console.log('测试按钮被点击')
      this.$message.success('测试按钮工作正常！')
    },

    // 显示上传对话框
    showUploadDialog() {
      console.log('showUploadDialog 方法被调用')
      this.uploadDialogVisible = true
      console.log('uploadDialogVisible 设置为:', this.uploadDialogVisible)
             this.uploadForm = {
         soId: '',
         attachmentType: '',
         uploader: '',
         description: '',
         fileList: []
       }
      // 延迟执行，确保对话框完全渲染后再清除验证
      setTimeout(() => {
        console.log('延迟执行回调')
        if (this.$refs.uploadForm) {
          this.$refs.uploadForm.clearValidate()
          console.log('表单验证已清除')
        } else {
          console.log('uploadForm 引用不存在')
        }
      }, 100)
    },

    // 上传前验证
    beforeUpload(file) {
      console.log('上传前验证文件:', file.name, file.size)
      // 检查文件大小 - 与后端限制保持一致 (10MB)
      const maxSize = 10 * 1024 * 1024 // 10MB (10485760 bytes)
      if (file.size > maxSize) {
        this.$message.error(`文件大小不能超过10MB，当前文件：${(file.size / 1024 / 1024).toFixed(2)}MB`)
        return false
      }
      console.log('文件验证通过:', file.name)
      return true
    },

    // 文件选择变化
    handleFileChange(file, fileList) {
      console.log('文件选择变化:', file)
      console.log('文件对象:', file.raw)
      console.log('文件列表:', fileList)
      
      // 确保每个文件对象都包含原始文件，并验证文件完整性
      fileList.forEach(f => {
        if (!f.raw && file.raw && f.uid === file.uid) {
          f.raw = file.raw
        }
        
        // 验证文件完整性
        if (f.raw) {
          console.log(`文件 ${f.name} 详细信息:`, {
            name: f.raw.name,
            size: f.raw.size,
            type: f.raw.type,
            lastModified: f.raw.lastModified
          })
          
                     // 检查文件大小是否合理
           if (f.raw.size < 100) { // 小于100字节的文件可能有问题
             console.warn(`警告：文件 ${f.name} 大小异常：${f.raw.size} 字节`)
           }
           
           // 检查文件大小是否超过后端限制
           const maxSize = 10 * 1024 * 1024 // 10MB
           if (f.raw.size > maxSize) {
             console.warn(`警告：文件 ${f.name} 超过大小限制：${f.raw.size} 字节 (最大10MB)`)
           }
        }
      })
      
      this.uploadForm.fileList = fileList
      console.log('当前文件列表:', this.uploadForm.fileList)
      console.log('文件列表长度:', this.uploadForm.fileList.length)
      
      // 验证文件
      this.validateFiles(fileList)
    },
    
    // 验证文件
    validateFiles(fileList) {
      const validFiles = fileList.filter(file => {
        const isValid = file.raw && file.raw instanceof File
        console.log(`文件 ${file.name} 验证结果:`, isValid, file.raw)
        
                 if (isValid) {
           // 额外验证文件大小
           if (file.raw.size < 100) {
             console.warn(`文件 ${file.name} 大小异常：${file.raw.size} 字节`)
             this.$message.warning(`文件 ${file.name} 大小异常，可能已损坏`)
             return false
           }
           
           // 检查文件大小是否超过后端限制
           const maxSize = 10 * 1024 * 1024 // 10MB
           if (file.raw.size > maxSize) {
             console.warn(`文件 ${file.name} 超过大小限制：${file.raw.size} 字节 (最大10MB)`)
             this.$message.warning(`文件 ${file.name} 超过大小限制，请选择小于10MB的文件`)
             return false
           }
         }
        
        return isValid
      })
      console.log('有效文件数量:', validFiles.length)
      
      if (validFiles.length === 0) {
        this.$message.warning('请选择有效的文件')
      }
    },

    // 移除文件
    handleFileRemove(file, fileList) {
      console.log('移除文件:', file, fileList)
      this.uploadForm.fileList = fileList
      console.log('移除后文件列表:', this.uploadForm.fileList)
    },
    
    // 清空文件
    clearFiles() {
      this.uploadForm.fileList = []
      console.log('文件列表已清空')
    },
    
    // 重新选择文件
    reSelectFiles() {
      this.uploadForm.fileList = []
      console.log('请重新选择文件')
      this.$message.info('请重新选择文件')
    },

    // 验证订单ID
    validateSoId(value) {
      // 移除非数字字符
      this.uploadForm.soId = value.replace(/\D/g, '')
    },

    // 提交上传
    async submitUpload() {
      console.log('开始提交上传')
      console.log('表单数据:', this.uploadForm)
      console.log('文件列表:', this.uploadForm.fileList)
      
      // 检查认证状态
      if (!this.checkAuthStatus()) {
        return
      }
      
      // 验证订单ID格式
      if (!this.uploadForm.soId || !/^\d+$/.test(this.uploadForm.soId)) {
        this.$message.error('请输入有效的订单ID（必须是数字）')
        return
      }
      
      this.$refs.uploadForm.validate(async (valid) => {
        if (!valid) {
          console.log('表单验证失败')
          return
        }
        
        if (!this.uploadForm.fileList || this.uploadForm.fileList.length === 0) {
          this.$message.warning('请选择要上传的文件')
          console.log('没有选择文件')
          return
        }

        console.log('开始上传，文件数量:', this.uploadForm.fileList.length)
        this.uploading = true
        
                 try {
           // 提取原始文件对象
           const rawFiles = this.uploadForm.fileList.map(file => file.raw || file)
           console.log('原始文件对象:', rawFiles)
           console.log('文件数量:', rawFiles.length)
           
                       // 检查文件对象是否有效
            const validFiles = rawFiles.filter(file => file && file instanceof File)
            console.log('有效文件数量:', validFiles.length)
            
            if (validFiles.length === 0) {
              this.$message.error('没有有效的文件可以上传')
              return
            }
            
            // 打印每个文件的详细信息并验证文件完整性
            const finalValidFiles = []
            validFiles.forEach((file, index) => {
              console.log(`AttachmentManagement: 文件 ${index + 1} 详细信息:`, {
                name: file.name,
                size: file.size,
                type: file.type,
                lastModified: file.lastModified,
                constructor: file.constructor.name,
                isFile: file instanceof File,
                hasOwnProperty: {
                  name: file.hasOwnProperty('name'),
                  size: file.hasOwnProperty('size'),
                  type: file.hasOwnProperty('type')
                }
              })
              
              // 验证文件大小
              if (file.size < 100) {
                console.warn(`文件 ${file.name} 大小异常：${file.size} 字节，跳过上传`)
                this.$message.warning(`文件 ${file.name} 大小异常，已跳过`)
              } else if (file.size > 10 * 1024 * 1024) {
                console.warn(`文件 ${file.name} 超过大小限制：${file.size} 字节，跳过上传`)
                this.$message.warning(`文件 ${file.name} 超过10MB限制，已跳过`)
              } else {
                finalValidFiles.push(file)
                console.log(`文件 ${file.name} 验证通过，已添加到最终列表`)
              }
            })
            
            if (finalValidFiles.length === 0) {
              this.$message.error('没有有效的文件可以上传')
              return
            }
            
                        console.log('最终有效文件数量:', finalValidFiles.length)
            
            // 添加这行日志，查看最终传递给API的文件列表
            console.log('AttachmentManagement: 最终有效文件列表 (传递给API):', finalValidFiles)
            
            // 使用正确的API调用方式，传递所有必要参数
            console.log('准备调用API，参数:', {
              soId: this.uploadForm.soId,
              filesCount: finalValidFiles.length,
              description: this.uploadForm.description,
              uploader: this.uploadForm.uploader
            })
            
            const response = await salesApi.fileApi.uploadAttachments(
              this.uploadForm.soId, 
              finalValidFiles, 
              this.uploadForm.description,
              this.uploadForm.uploader
            )
           
           console.log('上传响应:', response)
           
                                             if (response.success) {
              console.log('上传成功，响应数据:', response.data)
              if (response.data && response.data.length > 0) {
                this.$message.success(`批量上传成功，共上传 ${response.data.length} 个文件`)
              } else {
                this.$message.warning('上传成功，但没有文件被保存，请检查后端日志')
                
                // 显示详细提示
                this.$alert(
                  `上传成功但文件未保存！\n\n可能的原因：\n1. 后端文件验证失败\n2. 文件保存路径问题\n3. 数据库连接问题\n\n请检查后端控制台日志获取详细信息。`,
                  '上传警告',
                  {
                    confirmButtonText: '确定',
                    type: 'warning',
                    dangerouslyUseHTMLString: true
                  }
                )
              }
              this.uploadDialogVisible = false
              this.loadAttachments()
                        } else {
               console.error('上传失败，响应:', response)
               
               // 检查是否是网络连接错误
               if (response.message && response.message.includes('网络连接失败')) {
                 this.$message.error('网络连接失败，请检查后端服务是否启动')
                 console.error('详细错误信息:', response.details)
                 
                 // 显示更详细的错误信息
                 this.$alert(
                   `网络连接失败！\n\n可能的原因：\n1. 后端服务未启动\n2. 端口8080被占用\n3. 防火墙阻止连接\n\n请检查后端服务状态后重试。`,
                   '连接错误',
                   {
                     confirmButtonText: '确定',
                     type: 'error',
                     dangerouslyUseHTMLString: true
                   }
                 )
                 return
               }
               
               // 检查是否是认证错误
               if (response.message && response.message.includes('认证')) {
                 this.$message.error('认证失败，请重新登录')
                 localStorage.removeItem('token')
                 this.$router.push('/')
               } 
               // 检查是否是数据类型错误
               else if (response.message && response.message.includes('NumberFormatException')) {
                 this.$message.error('订单ID格式错误，请输入有效的数字')
               }
               // 检查是否是订单ID相关错误
               else if (response.message && response.message.includes('订单')) {
                 this.$message.error('订单ID无效，请检查后重试')
               }
               // 检查是否是文件相关错误
               else if (response.message && (response.message.includes('文件') || response.message.includes('不支持') || response.message.includes('大小'))) {
                 this.$message.error(`文件上传失败：${response.message}`)
                 
                 // 显示文件错误详情
                 this.$alert(
                   `文件上传失败！\n\n错误详情：${response.message}\n\n请检查：\n1. 文件大小是否超过10MB\n2. 文件类型是否支持\n3. 文件是否损坏\n\n支持的文件类型：PDF、DOC、DOCX、XLS、XLSX、JPG、PNG、ZIP等`,
                   '文件错误',
                   {
                     confirmButtonText: '确定',
                     type: 'error',
                     dangerouslyUseHTMLString: true
                   }
                 )
               }
               else {
                 this.$message.error(response.message || '批量上传失败')
               }
             }
         } catch (error) {
           console.error('批量上传失败:', error)
           // 检查是否是认证错误
           if (error.message && error.message.includes('401')) {
             this.$message.error('认证失败，请重新登录')
             localStorage.removeItem('token')
             this.$router.push('/')
           } else {
             this.$message.error('批量上传失败')
           }
         } finally {
           this.uploading = false
         }
      })
    },

    // 编辑描述
    editDescription(file) {
      this.editForm = {
        id: file.id,
        attachmentName: file.attachmentName,
        description: file.description || ''
      }
      this.editDialogVisible = true
    },

    // 提交编辑
    async submitEdit() {
      this.$refs.editForm.validate(async (valid) => {
        if (!valid) return
        
        try {
          const response = await salesApi.attachmentApi.updateAttachmentDescription(
            this.editForm.id,
            this.editForm.description
          )
          if (response.success) {
            this.$message.success('描述更新成功')
            this.editDialogVisible = false
            this.loadAttachments()
          } else {
            this.$message.error(response.message || '描述更新失败')
          }
        } catch (error) {
          console.error('更新描述失败:', error)
          this.$message.error('更新描述失败')
        }
      })
    },

         // 预览文件
     async previewFile(file) {
       this.previewFileData = file
       this.previewDialogVisible = true
      
      try {
        const response = await salesApi.fileApi.previewAttachment(file.id)
        if (response.success) {
          // 创建预览URL
          const blob = new Blob([response.data])
          this.previewUrl = URL.createObjectURL(blob)
        } else {
          this.$message.error('文件预览失败')
        }
      } catch (error) {
        console.error('文件预览失败:', error)
        this.$message.error('文件预览失败')
      }
    },

         // 下载预览文件
     downloadPreviewFile() {
       const link = document.createElement('a')
       link.href = this.previewUrl
       link.download = this.previewFileData.attachmentName
       link.click()
     },

         // 打印预览文件
     printPreviewFile() {
       if (this.isImageFile) {
         const printWindow = window.open('', '_blank')
         printWindow.document.write(`
           <html>
             <head><title>${this.previewFileData.attachmentName}</title></head>
             <body>
               <img src="${this.previewUrl}" style="max-width: 100%; height: auto;" />
             </body>
           </html>
         `)
         printWindow.document.close()
         printWindow.print()
       } else {
         this.$message.warning('当前文件类型不支持打印预览')
       }
     },

    // 删除单个文件
    async deleteFile(file) {
      this.$confirm('确定要删除这个附件吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await salesApi.fileApi.deleteAttachment(file.id)
          if (response.success) {
            this.$message.success('删除成功')
            this.loadAttachments()
          } else {
            this.$message.error(response.message || '删除失败')
          }
        } catch (error) {
          console.error('删除文件失败:', error)
          this.$message.error('删除文件失败')
        }
      })
    },

    // 删除选中的文件
    async deleteSelected() {
      if (this.selectedAttachments.length === 0) {
        this.$message.warning('请选择要删除的附件')
        return
      }

      this.$confirm(`确定要删除选中的 ${this.selectedAttachments.length} 个附件吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const ids = this.selectedAttachments.map(item => item.id)
          const response = await salesApi.fileApi.deleteAttachments(ids)
          if (response.success) {
            this.$message.success('批量删除成功')
            this.selectedAttachments = []
            this.loadAttachments()
          } else {
            this.$message.error(response.message || '批量删除失败')
          }
        } catch (error) {
          console.error('批量删除失败:', error)
          this.$message.error('批量删除失败')
        }
      })
    },

    // 导出选中的附件
    async exportSelected() {
      if (this.selectedAttachments.length === 0) {
        this.$message.warning('请选择要导出的附件')
        return
      }

      try {
        const ids = this.selectedAttachments.map(item => item.id)
        const response = await salesApi.fileApi.downloadAttachmentsAsZip(ids)
        if (response.success) {
          this.$message.success('导出成功')
        } else {
          this.$message.error(response.message || '导出失败')
        }
      } catch (error) {
        console.error('导出附件失败:', error)
        this.$message.error('导出附件失败')
      }
    },

    // 打印选中的附件
    printSelected() {
      if (this.selectedAttachments.length === 0) {
        this.$message.warning('请选择要打印的附件')
        return
      }

      // 这里可以实现批量打印逻辑
      this.$message.info('批量打印功能开发中...')
    },

    // 选择变化
    handleSelectionChange(selection) {
      this.selectedAttachments = selection
    },

    // 分页大小变化
    handleSizeChange(size) {
      this.pagination.pageSize = size
      this.pagination.pageNo = 1
      this.loadAttachments()
    },

    // 当前页变化
    handleCurrentChange(page) {
      this.pagination.pageNo = page
      this.loadAttachments()
    },

    // 获取文件扩展名
    getFileExtension(fileName) {
      if (!fileName || !fileName.includes('.')) return ''
      return fileName.substring(fileName.lastIndexOf('.') + 1)
    },

    // 获取类型标签样式
    getTypeTagType(type) {
      const typeMap = {
        'CONTRACT': 'primary',
        'INVOICE': 'success',
        'DELIVERY': 'warning',
        'QUALITY': 'info',
        'OTHER': 'info'  // 改为 'info' 而不是 'default'
      }
      return typeMap[type] || 'info'  // 默认返回 'info' 而不是 'default'
    },

    // 获取类型名称
    getTypeName(typeCode) {
      if (!typeCode) return '未知类型'
      const type = this.attachmentTypes.find(t => t.typeCode === typeCode)
      return type ? type.typeName : typeCode
    },

    // 获取类型名称
    getTypeName(type) {
      const typeMap = {
        'CONTRACT': '合同文件',
        'INVOICE': '发票文件',
        'DELIVERY': '送货单',
        'QUALITY': '质检报告',
        'OTHER': '其他文件'
      }
      return typeMap[type] || type
    },

    // 格式化文件大小
    formatFileSize(bytes) {
      if (bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    },

    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return ''
      const date = new Date(dateTime)
      return date.toLocaleString('zh-CN')
    }
  }
}
</script>

<style scoped>
.attachment-management {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 60px);
}

/* 确保对话框正常显示 */
:deep(.el-dialog) {
  z-index: 2000 !important;
}

:deep(.el-dialog__wrapper) {
  z-index: 1999 !important;
}

/* 调试样式 */
.debug-info {
  background-color: #f0f0f0;
  padding: 10px;
  border: 1px solid #ccc;
  margin-bottom: 10px;
  border-radius: 4px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-title {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.auth-status {
  display: flex;
  align-items: center;
}

.action-section {
  display: flex;
  gap: 10px;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-form {
  margin: 0;
}

.attachment-list {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.pagination-section {
  padding: 20px;
  text-align: center;
  background-color: white;
}

.preview-content {
  padding: 20px;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.preview-header h3 {
  margin: 0;
  color: #303133;
}

.preview-actions {
  display: flex;
  gap: 10px;
}

.preview-body {
  min-height: 400px;
}

.image-preview {
  text-align: center;
}

.image-preview img {
  max-width: 100%;
  max-height: 600px;
  object-fit: contain;
}

.pdf-preview {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.other-preview {
  text-align: center;
  padding: 40px;
}

.file-info {
  color: #606266;
}

.file-info .file-icon {
  font-size: 48px;
  color: #c0c4cc;
  margin-bottom: 20px;
}

.file-info p {
  margin: 10px 0;
  font-size: 14px;
}

.file-list-info {
  margin-top: 10px;
  padding: 12px;
  background-color: #f0f9ff;
  border: 1px solid #bae6fd;
  border-radius: 4px;
  color: #0369a1;
  font-size: 14px;
}

.file-details {
  margin-top: 8px;
  text-align: left;
}

.file-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 0;
  border-bottom: 1px solid #e0f2fe;
}

.file-item:last-child {
  border-bottom: none;
}

.file-name {
  flex: 1;
  font-weight: 500;
}

.file-size {
  margin: 0 10px;
  color: #64748b;
  font-size: 12px;
}

.file-status {
  font-size: 12px;
  font-weight: 500;
}

.file-status.valid {
  color: #059669;
}

.file-status.invalid {
  color: #dc2626;
}

.file-actions {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #e0f2fe;
  text-align: center;
}

.file-actions .el-button {
  margin: 0 5px;
}

.form-tip {
  margin-top: 5px;
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 15px;
  }
  
  .action-section {
    flex-wrap: wrap;
    justify-content: center;
  }
  
  .search-form {
    display: block;
  }
  
  .search-form .el-form-item {
    display: block;
    margin-bottom: 15px;
  }
}
</style>
